const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const rp = require('./requestProxy');
const builder = require('./outputDataBuilder');

const router = express.Router();

const dicCondition = require('./dicCondition');
const dicRequestChartData = require('./dicRequestChartData');
const dicAPIUrl = require('./dicAPIUrl');

// parse application/json
router.use(bodyParser.json());

// 老师-筛选条件
router.get(/^\/condition\/([\w|-]+)\/(?:(\w+))?$/, (req, res) => {
	'use strict';

	let key = req.params[0];
	let data = req.params[1];
	let parameter = undefined;

	if (dicCondition[key])
		parameter = dicCondition[key](data);

	if (!parameter) {
		res.status(404).json(rp.dataPack(`key '${key}' is invalid`, true));
		return false;
	}

	rp.post(dicAPIUrl['condition'], parameter)
		.then((data) => {
			res.json(rp.dataPack(data));
		})
		.catch((err) => {
			res.json(rp.dataPack(data, true));
		});
});

// 布置作业-老师-题目-新增趋势
router.post('/data/:chartName', (req, res) => {
	'use strict';

	let key = req.params.chartName,
		postRequestData = undefined,
		api = dicAPIUrl[key],
		buildhandler = builder[key];

	if (dicRequestChartData[key])
		postRequestData = dicRequestChartData[key](req.body);

	if (!api) {
		res.status(404).json(rp.dataPack(`key '${key}' is invalid for chart data api`, true));
		return false;
	}

	if (!buildhandler) {
		res.status(404).json(rp.dataPack(`key '${key}' is invalid for chart data builder`, true));
		return false;
	}

	if (!postRequestData) {
		res.status(404).json(rp.dataPack(`key '${key}' is invalid for chart data condition`, true));
		return false;
	}

	let isFinished = false, parameters = [];

	postRequestData.forEach((item) => {

		console.log(`fetch target is ${api}`, item);

		rp.post(api, item)
			.then((data) => {
				parameters.push(data);
				if (parameters.length == postRequestData.length) {
					let result = buildhandler.apply(null, parameters);
					res.json(rp.dataPack(result));
				}
			})
			.catch(function(err) {
				if (!isFinished) {
					debugger;
					isFinished = true;
					res.json(rp.dataPack(err, true));
				}
			}.bind(item))
	});
});

module.exports = router;